package com.xiake.zojcodesandbox.controller;

import com.xiake.zojcodesandbox.JavaDockerCodeSandbox;
import com.xiake.zojcodesandbox.JavaNativeCodeSandbox;
import com.xiake.zojcodesandbox.model.ExecuteCodeRequest;
import com.xiake.zojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class ProcessController {
    @Resource
   // private JavaDockerCodeSandbox javaDockerCodeSandbox;
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";

    @PostMapping("/processCode")
    public ExecuteCodeResponse processCode(@RequestBody ExecuteCodeRequest executeCodeRequest,HttpServletRequest request,
                                           HttpServletResponse response) {
        // TODO: 可以将返回信息封装成统一格式，方便前端处理
        // 基本的认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        return executeCodeResponse;
    }
}
